//
//  inviteQRCodeController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 2017/3/14.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "inviteQRCodeController.h"
#import "SGQRCodeTool.h"
#import "HJCActionSheet.h"
#import "inviteCodeModel.h"
#import "InviteListController.h"

#define BLUECOLOR  RGB(68,108,226)



@interface inviteQRCodeController ()<HJCActionSheetDelegate>
{
     MBProgressHUD *_progressHUD;
}

@property (nonatomic, strong) UIImageView *customImageView;

@property(nonatomic,strong)NSString *inviteCodeStr;

@property(nonatomic,strong)NSString *inviteCodeUrlStr;

@property(nonatomic,strong)inviteCodeModel *inviteModel;

@end

@implementation inviteQRCodeController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getQRCodeDataRequest];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithBackgroundImage:[UIImage imageNamed:@"icon_Qrshare"] highBackgroundImage:nil target:self action:@selector(shareDidClick) title:nil];
    
    self.title = @"邀请码";
    self.view.backgroundColor = [UIColor whiteColor];
    
   
}


#pragma mark 请求
- (void)getQRCodeDataRequest
{
    _progressHUD = [MBProgressHUD show:self.view andMessage:nil];
    [self.view addSubview:_progressHUD];
    
    NSDictionary *params = @{@"username":USERNAME};
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/expand/userToken" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            NSDictionary *tempDict = [object objectForKey:@"data"];
            self.inviteModel = [[inviteCodeModel alloc] initWithDictionary:tempDict error:nil];
            
            self.inviteCodeStr = self.inviteModel.extends_sn;
            self.inviteCodeUrlStr = self.inviteModel.extends_url;

            [self buildViewinviteStr:_inviteModel.extends_sn inviteUrlStr:_inviteModel.extends_url];
            [_progressHUD hide:YES];
        }else{
            
            _progressHUD = [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",[object[@"message"] objectForKey:@"view"]] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:_progressHUD];
        }
    }];
    
}

- (void)dealloc{
    [_progressHUD removeFromSuperViewOnHide];
}


#pragma mark 查看邀请人记录

- (void)inviteListDidClick
{
    InviteListController *inviteListVC = [[InviteListController alloc] init];
    [self.navigationController pushForm:self.navigationController pushToAndHidden:inviteListVC];
}


#pragma mark 分享
- (void)shareDidClick
{
    
    
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.isShow = false;
    
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),
                                               @(UMSocialPlatformType_WechatSession),
                                               @(UMSocialPlatformType_WechatTimeLine),
                                               @(UMSocialPlatformType_WechatFavorite)
                                               ]];
    
    //设置分享面板的显示和隐藏的代理回调
    //    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        NSLog(@"%zd",platformType);
        
        [self shareTypeNameWithType:platformType];
    }];
}

//分享类型
- (void)shareTypeNameWithType:(NSInteger)typeIndex
{
    switch (typeIndex) {
        case 4:
        {
            [self shareImageToPlatformType:UMSocialPlatformType_QQ];
        }
            break;
        case 1:
        {
            [self shareImageToPlatformType:UMSocialPlatformType_WechatSession];
        }
            break;
        case 2:
        {
            [self shareImageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
            break;
        case 3:
        {
            [self shareImageToPlatformType:UMSocialPlatformType_WechatFavorite];
        }
            break;
            
        default:
            break;
    }
    
}

- (void)shareImageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    //    NSString* thumbURL =  EASY_THUMB_IMAGE;
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"可为建材联盟" descr:@"可为建材联盟" thumImage:self.customImageView.image];
    //设置网页地址
    shareObject.webpageUrl = self.inviteCodeUrlStr;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        
    }];
}


#pragma mark 邀请码
- (void)copyButtonDidClick
{
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitles:@"复制邀请码", @"复制链接", @"保存二维码到相册", nil];
    [sheet show];
}

//实现HJCActionSheetDelegate代理
- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    UIPasteboard *copyStr = [UIPasteboard generalPasteboard];
    
    if (buttonIndex == 2) {
        copyStr.string = self.inviteCodeUrlStr;
    }else if (buttonIndex == 1){
        copyStr.string = self.inviteCodeStr;
    }else{
        
    }
   
    switch (buttonIndex) {
        case 1:
            //邀请码
            if (copyStr == nil || [self.inviteCodeStr isEqualToString:@""] == true){
                _progressHUD = [MBProgressHUD showMessage:@"复制邀请码失败" toView:self.view dimBackground:false AndCompleteBlock:nil];
            }else{
                _progressHUD = [MBProgressHUD showMessage:@"复制邀请码成功" toView:self.view dimBackground:false AndCompleteBlock:nil];
            }
            break;
        case 2:
            //链接
            if (copyStr == nil || [self.inviteCodeUrlStr isEqualToString:@""] == true){
                _progressHUD = [MBProgressHUD showMessage:@"复制链接失败" toView:self.view dimBackground:false AndCompleteBlock:nil];
            }else{
                _progressHUD = [MBProgressHUD showMessage:@"复制链接成功" toView:self.view dimBackground:false AndCompleteBlock:nil];
            }
            
            
            break;
        case 3:
            //保存至相册
            [self photoAlbumQX:self.customImageView.image];
        break;
    }
}

//相册权限
- (void)photoAlbumQX:(UIImage *)image
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusDenied) {
        //相册权限未开启
        [self showAlertViewToController:self.navigationController];
        
    }else if(status == PHAuthorizationStatusNotDetermined){
        //相册进行授权
        /* * * 第一次安装应用时直接进行这个判断进行授权 * * */
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
            //授权后
            if (status == PHAuthorizationStatusAuthorized){
                dispatch_async(dispatch_get_main_queue(), ^{
                    //保存图片
                    [self saveImageToPhotos:image];
                });
                
            }
        }];
    }else if (status == PHAuthorizationStatusAuthorized){
        
        [self saveImageToPhotos:image];
    }
    
    
}


//图片保存
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
}
//回调
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"收款二维码已下载到您的手机相册" ;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showMessage:msg toView:self.view dimBackground:NO AndCompleteBlock:nil];
    [self.view addSubview:hud];
}

-(void)showAlertViewToController:(UIViewController *)controller
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:[NSString stringWithFormat:@"请在iPhone的“设置->隐私->照片”开启%@访问你的手机相册",app_Name] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        
    }];
    
    [alert addAction:action1];
    [controller presentViewController:alert animated:YES completion:nil];
}



- (void)buildViewinviteStr:(NSString *)inviteStr inviteUrlStr:(NSString *)inviteUrlStr
{
    CGFloat imageW = WIDTH/3*2;
    CGFloat marginX = WIDTH/6;
    CGFloat marginY = HEIGHT/20;
    
    //邀请二维码
    UILabel *topLbl = [[UILabel alloc] init];
    topLbl.text = @"邀请二维码";
    topLbl.textColor = [UIColor grayColor];
    [self.view addSubview:topLbl];
    topLbl.font = BOLDFONT(15);
    
    [topLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(marginY);
        make.left.equalTo(self.view.mas_left).offset(marginX);
    }];
    
    //查看邀请人记录
    UIButton *inviteListBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [inviteListBtn setTitle:@"查看邀请人记录" forState:UIControlStateNormal];
    [inviteListBtn setTitleColor:DEFAULT_COLOR forState:UIControlStateNormal];
    [self.view addSubview:inviteListBtn];
    [inviteListBtn.titleLabel sizeToFit];
    inviteListBtn.titleLabel.font = BOLDFONT(15);
    [inviteListBtn addTarget:self action:@selector(inviteListDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    [inviteListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topLbl.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-marginX);
//        make.height.mas_equalTo(15);
    }];
    
    //二维码
    [self.view addSubview:self.customImageView];
    [self.customImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(topLbl.mas_bottom).offset(marginY);
        make.width.height.mas_equalTo(imageW);
    }];
    
    //
    CGFloat scale = 0.2;
    NSString *urlStr = inviteUrlStr;
    self.customImageView.image = [SGQRCodeTool SG_generateWithLogoQRCodeData:urlStr logoImageName:@"icon" logoScaleToSuperView:scale];
    
    //我的邀请码
    UILabel *bottomLbl = [[UILabel alloc] init];
    bottomLbl.text = @"我的邀请码";
    bottomLbl.textColor = [UIColor grayColor];
    [self.view addSubview:bottomLbl];
    bottomLbl.font = BOLDFONT(14);
    
    [bottomLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customImageView.mas_bottom).offset(marginY);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    //邀请码
    UILabel *inviteCodeLbl = [[UILabel alloc] init];
    inviteCodeLbl.text = inviteStr;
    inviteCodeLbl.textColor = [UIColor whiteColor];
    [self.view addSubview:inviteCodeLbl];
    inviteCodeLbl.backgroundColor = BLUECOLOR;
    inviteCodeLbl.textAlignment = NSTextAlignmentCenter;
    inviteCodeLbl.layer.masksToBounds = true;
    inviteCodeLbl.layer.cornerRadius = 10;
    inviteCodeLbl.font = [UIFont fontWithName:@"Arial-BoldMT" size:30];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:inviteCodeLbl.font forKey:NSFontAttributeName];
    CGSize btnSize = [inviteStr sizeWithAttributes:attributes];
    
    [inviteCodeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(bottomLbl.mas_bottom).offset(10);
        make.height.mas_equalTo(btnSize.height + 20);
        make.width.mas_equalTo(btnSize.width + 25);
    }];
    
    
    //复制按钮
    UIButton *copyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [copyButton setTitle:@"复制邀请码" forState:UIControlStateNormal];
    [copyButton setTitleColor:DEFAULT_COLOR forState:UIControlStateNormal];
    [self.view addSubview:copyButton];
    [copyButton.titleLabel sizeToFit];
    copyButton.titleLabel.font = BOLDFONT(15);
    [copyButton addTarget:self action:@selector(copyButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    [copyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(inviteCodeLbl.mas_bottom).offset(20);
         make.centerX.equalTo(self.view.mas_centerX);
    }];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (UIImageView *)customImageView
{
    if (!_customImageView) {
        _customImageView = [[UIImageView alloc] init];
        _customImageView.layer.borderWidth = 2.0f;
        _customImageView.layer.borderColor = BACKGROUND_COLOR.CGColor;
    }
    return _customImageView;
}




@end
